package org.misty.seckill.resolver;

import org.misty.seckill.model.User;
import org.misty.seckill.service.LoginService;
import org.misty.seckill.util.ServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
  @Autowired
  private LoginService loginService;

  @Override
  public boolean supportsParameter(MethodParameter parameter) {
    return parameter.getParameterType() == User.class;
  }

  @Override
  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
    var request = webRequest.getNativeRequest(HttpServletRequest.class);
    if (request != null) {
      var token = ServletUtil.readSessionToken(request);
      return loginService.getByToken(token);
    }
    return null;
  }
}
